package com.dealer.management.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dealer.management.common.Result;
import com.dealer.management.entity.Customer;
import com.dealer.management.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("/page")
    public Result<IPage<Customer>> getCustomerPage(@RequestParam(defaultValue = "1") Integer current,
                                                   @RequestParam(defaultValue = "10") Integer size,
                                                   @RequestParam(required = false) String name) {
        Page<Customer> page = new Page<>(current, size);
        IPage<Customer> customerPage = customerService.getCustomerPage(page, name);
        return Result.success(customerPage);
    }

    @GetMapping("/{id}")
    public Result<Customer> getCustomerById(@PathVariable Long id) {
        Customer customer = customerService.getCustomerById(id);
        return customer != null ? Result.success(customer) : Result.error("客户不存在");
    }

    @PostMapping
    public Result<Boolean> saveCustomer(@RequestBody Customer customer) {
        boolean result = customerService.saveCustomer(customer);
        return result ? Result.success(true) : Result.error("保存失败");
    }

    @PutMapping
    public Result<Boolean> updateCustomer(@RequestBody Customer customer) {
        boolean result = customerService.updateCustomer(customer);
        return result ? Result.success(true) : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCustomer(@PathVariable Long id) {
        boolean result = customerService.deleteCustomer(id);
        return result ? Result.success(true) : Result.error("删除失败");
    }
}
